import cv2, pywinauto, random, time
from datetime import datetime, timedelta
import fishing_util,screen_cap,wow_hijack


PATH = r"E:\Game\World of Warcraft\_classic_\WowClassic.exe"
FISHING_ENABLED = True
TRACKBARS = False
SHOW_VIDEO_FEED = True
NEW_CAST_THRESHOLD = 20


def bobber_screen_coords(bobber_location, app_height, app_position):
    ''' Returns the bobber x,y screen coordinates in a tuple.
        Takes into account window x,y offset if not fullscreen.
            ARGS:       bobber_location (tuple(X,Y))
            RETURNS:    screen_coords (tuple(X,Y)) '''
    screen_coords = (int(bobber_location[0]+ app_position.left),int(bobber_location[1]+(app_height/5*3)))
    return screen_coords

def main():
    wow_running = wow_hijack.check_process(["World of Warcraft", "WorldOfWarcraft", "Wow.exe","WowClassic.exe"])
    print(f'[+] Finding WoW application instance.')
    if wow_running:
        try:
            # Connect to WoW
            app = wow_hijack.connect_app(PATH)
            # Get window position and height
            app_position = wow_hijack.get_app_pos(app)

            app_height = app_position.height()
            # Fishing only requires the bottom 2/5 of the screen
            # Adjust the window to 2/5 of the height
            adjusted_window = (app_position.left+10,(app_position.top+(app_height/5*3)),app_position.right-10, app_position.bottom-10)
        except Exception as e:
            print(f'[!] Can\'t connect to WoW instance.: {e}')
            print('[!] Exiting.')
            exit()
    else:
        print(f'[!] Can\'t find WoW instance running.')
        print('[!] Exiting.')
        exit()
    # Set up trackbars ( if you want to )
    if TRACKBARS:
        screen_cap.setup_trackbars()
    # Arbitrary value

    print("------ 开始钓鱼 按`q`退出 ------")
    last_bobber_location = (0,0)
    last_cast = datetime.now()
    loopSecond= (time.time())
    while(True):
        try:
            # Retrieve video output and bobber location
            mask, output = screen_cap.generate_window(*adjusted_window)
            bobber_location = screen_cap.find_bobber(mask, output)
            if SHOW_VIDEO_FEED:
                cv2.imshow('FishingBot Feed', output)
            # If a bobber location is found
            if bobber_location:
                #print(bobber_location)
                # If X coord changes more than new_cast_threshold
                new_cast = fishing_util.check_new_cast(NEW_CAST_THRESHOLD, last_cast,last_bobber_location, bobber_location)
                if new_cast:
                    print('[+] New cast detected.')
                else:
                    # Check for variance in Y coords to see if bobber dips
                    upper_threshold = last_bobber_location[1] + 2  #7
                    lower_threshold = last_bobber_location[1] - 1  #5
                    #print(bobber_location[1] - last_bobber_location[1])
                    # Compare Y coordinates
                    if bobber_location[1] > upper_threshold or bobber_location[1] < lower_threshold:
                        # This is where the code will go to catch the fish
                        # @ given X,Y coords, and then press the button to
                        # restart the fishing process
                        if datetime.now() > (last_cast+timedelta(seconds=3)):
                            # Debug
                            print('[+] Fish On!')
                            if FISHING_ENABLED:
                                # Potentially get this on a different thread
                                # Sleep for random amt of time
                                time.sleep(random.uniform(0.8,2.15))
                                # Get screen coords from window coords for mouse click
                                coords = bobber_screen_coords(bobber_location,app_height,app_position)
                                # Click at selected coordinates
                                fishing_util.click(coords)
                                # Sleep for random amt of time
                                time.sleep(random.uniform(1.5, 3.3))
                                last_cast = fishing_util.cast(coords)
                # Update last known bobber location
                last_bobber_location = bobber_location
            else:
                if (loopSecond != (time.time())):
                    print('[-] Cant find bobber!')
                if datetime.now()- last_cast >timedelta(seconds=30):
                    coords = bobber_screen_coords((100,100), app_height, app_position)
                    last_cast = fishing_util.cast(coords)
            # Exit key == 'q'
            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break
            loopSecond = (time.time())
        except KeyboardInterrupt:
            cv2.destroyAllWindows()
            break

def loadUserParamters():
    import os, sys,json
    if hasattr(sys.modules[__name__], '__file__'):
        _file_name = __file__
    else:
        from . import __file__ as _file_name
    PROJECT_PATH = os.path.dirname(os.path.realpath(_file_name))
    usercfg = {
        'PATH': PATH,
        'FISHING_ENABLED': FISHING_ENABLED,
        'SHOW_VIDEO_FEED': SHOW_VIDEO_FEED,
        'NEW_CAST_THRESHOLD': NEW_CAST_THRESHOLD
    }
    _fileCfgLoc = os.path.join(PROJECT_PATH, 'config.json')

    if os.path.isfile(_fileCfgLoc):
        try:
            with open(_fileCfgLoc ,encoding='utf-8') as json_data_file:
                tCFG = json.load(json_data_file)
                usercfg.update(tCFG)
        except:
            os.remove(_fileCfgLoc)
    else:

        with open(_fileCfgLoc, 'w',encoding='utf-8') as outfile:
            json.dump(usercfg, outfile,indent=4,ensure_ascii=False)
    print("---------config.json---------")
    import pprint
    pprint.pprint(usercfg)
    print("-----------------------------")

if __name__ == '__main__':

    print("** 设置鼠标中键为钓鱼")
    print("** 系统图形设置为最低画质，Ctrl+Z 隐藏界面")

    loadUserParamters()
    print("** 先不启动自动钓鱼，调整视角让水域在窗口下方(2/5面积)，并使水域部分都为黑色")
    print("** 等调整好视角后，重新运行程序，再选择自动钓鱼")
    userinput = input("是否自动钓鱼（0：否，1:是）:")
    FISHING_ENABLED = userinput if userinput in ('0','1') else FISHING_ENABLED
    print(FISHING_ENABLED)

    main()
    # 程序退出
    print("程序结束，5秒后退出")
    time.sleep(5)
